<template>
  <div>
    <div class="archive-container">
      <!-- 左侧树形导航 -->
      <div class="tree-container">
        <el-tree
            :data="treeData"
            :props="defaultProps"
            @node-click="handleNodeClick"
            default-expand-all
            highlight-current
            node-key="id"
            class="tree-content"
            :expand-on-click-node="false"
        ></el-tree>
      </div>

      <!-- 右侧内容区域 -->
      <div class="content-container">
        <!-- 操作栏 -->
        <div class="operation-bar">
          <div class="selected-category">
            {{ currentCategory ? currentCategory.label : '请选择文件类型' }}
            <span v-if="currentSubCategory"> > {{ currentSubCategory.label }}</span>
          </div>
          <div  class="search-group" v-if="showIncomingTable || showOutgoingTable">
              <el-input
                  class="search-input"
                  v-model="query.title"
                  placeholder="请输入文件标题"
                  clearable
              >
                <template slot="prepend">文件标题</template>
              </el-input>

              <el-input
                  class="search-input"
                  v-model="query.senderOrg"
                  :placeholder="showIncomingTable ? '请输入来文单位' : '请输入发文单位'"
                  clearable
              >
                <template slot="prepend">{{ showIncomingTable ? '来文单位' : '发文单位' }}</template>
              </el-input>

              <el-button
                  class="search-button"
                  type="primary"
                  icon="el-icon-search"
                  @click="handleSearch"
              >搜索</el-button>

              <el-button
                  class="reset-button"
                  icon="el-icon-refresh-left"
                  @click="resetSearch"
              >重置</el-button>
          </div>
        </div>

        <div>
          <el-button type="info" icon="el-icon-download" @click="exportData">导出数据</el-button>
        </div>

        <!-- 收文表格 -->
        <div v-if="showIncomingTable" class="table-container">
          <el-table
              :data="tableData"
              stripe
              border
              style="width: 100%"
              @selection-change="handleIncomingSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="fileNo" label="件号" width="100"></el-table-column>
            <el-table-column prop="senderDocNo" label="文件编号" width="120"></el-table-column>
            <el-table-column prop="title" label="文件标题" width="240"></el-table-column>
            <el-table-column prop="senderOrg" label="来文单位" width="180"></el-table-column>
            <el-table-column prop="secretLevel" label="密级" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.secretLevel === '普通'" type="success">普通</el-tag>
                <el-tag v-else type="danger">密级</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="urgencyLevel" label="紧急程度" width="120">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.urgencyLevel === '普通'" type="info">{{ scope.row.urgencyLevel }}</el-tag>
                <el-tag v-else type="warning">{{ scope.row.urgencyLevel }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="receiveDate" label="来文日期" width="120"></el-table-column>
            <el-table-column prop="handlingOrg" label="办件单位" width="180"></el-table-column>
            <el-table-column prop="processType" label="处理状态" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.processType === '已完成'" type="success">{{ scope.row.processType }}</el-tag>
                <el-tag v-else type="warning">{{ scope.row.processType }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="当前审批人" width="140">
              <template slot-scope="scope">
                <div class="current-approver" :class="{'approver-waiting': !scope.row.nextObjectName}">
                  {{ scope.row.nextObjectName || scope.row.objectName || '未分配' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="打印" width="140">
              <template v-slot="scope">
                <el-button :id="scope.row.id" type="warning" size="mini" @click="handleIncomingPrint(scope.row.id)">打印处理单</el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button class="detail-btn" size="mini" @click="handleDetail(scope.row, 'incoming')">详情</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
                :current-page="pageNum"
                :page-sizes="[10, 20, 50]"
                :page-size="pageSize"
                layout="total, prev, pager, next"
                :total="total"
                @current-change="handlePageChange"
            ></el-pagination>
          </div>
        </div>

        <!-- 发文表格 -->
        <div v-if="showOutgoingTable" class="table-container">
          <el-table
              :data="tableData"
              stripe
              border
              style="width: 100%"
              @selection-change="handleOutgoingSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="fileNo" label="件号" width="100"></el-table-column>
            <el-table-column prop="senderDocNo" label="发文编号" width="120"></el-table-column>
            <el-table-column prop="title" label="文件标题" width="240"></el-table-column>
            <el-table-column prop="senderOrg" label="发文单位" width="180"></el-table-column>
            <el-table-column prop="secretLevel" label="密级" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.secretLevel === '普通'" type="success">普通</el-tag>
                <el-tag v-else type="danger">密级</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createDate" label="发文日期" width="120">
              <template slot-scope="scope">
                {{ formatDate(scope.row.createDate) }}
              </template>
            </el-table-column>
            <el-table-column prop="handlingOrg" label="办件单位" width="180"></el-table-column>
            <el-table-column prop="archiveStatus" label="处理状态" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.archiveStatus === '已完成'" type="success">{{ scope.row.archiveStatus }}</el-tag>
                <el-tag v-else type="warning">{{ scope.row.archiveStatus }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="当前审批人" width="140">
              <template slot-scope="scope">
                <div class="current-approver" :class="{'approver-waiting': !scope.row.nextObjectName}">
                  {{ scope.row.nextObjectName || scope.row.objectName || '未分配' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button class="detail-btn" size="mini" @click="handleDetail(scope.row, 'outgoing')">详情</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
                :current-page="pageNum"
                :page-sizes="[10, 20, 50]"
                :page-size="pageSize"
                layout="total, prev, pager, next"
                :total="total"
                @current-change="handlePageChange"
            ></el-pagination>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!showIncomingTable && !showOutgoingTable" class="empty-container">
          <i class="el-icon-folder-opened empty-icon"></i>
          <div class="empty-text">请从左侧选择文件类型查看存档信息</div>
        </div>
      </div>
    </div>

    <!-- 收文详情对话框 -->
    <incoming-detail-dialog
        :visible="incomingDetailVisible"
        :doc-id="incomingDetailId"
        @close="incomingDetailVisible = false"
    />

    <!-- 发文详情对话框 -->
    <outgoing-detail-dialog
        :visible="outgoingDetailVisible"
        :doc-id="outgoingDetailId"
        @close="outgoingDetailVisible = false"
    />
  </div>
</template>

<script>
import IncomingDetailDialog from './IncomingDetailDialog.vue';
import OutgoingDetailDialog from './OutgoingDetailDialog.vue';
import * as XLSX from 'xlsx';
  export default {
    components: {
      IncomingDetailDialog,
      OutgoingDetailDialog
    },
    data() {
      return {
        treeData: [{
          id: 1,
          label: '收文',
          children: [{
            id: 11,
            label: '普通'
          }, {
            id: 12,
            label: '密件'
          }]
        }, {
          id: 2,
          label: '发文',
          children: [{
            id: 21,
            label: '普通'
          }, {
            id: 22,
            label: '密件'
          }]
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        currentCategory: null,
        currentSubCategory: null,
        showIncomingTable: false,
        showOutgoingTable: false,
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 0,
        detailDialogVisible: false,
        currentDetail: null,
        query: {
          title: '',          // 文件标题（模糊查询）
          senderOrg: '',      // 来文单位（模糊查询）
          processType: '',    // 处理状态（精确查询）
          archiveStatus : '',
          secretType: null // 密件类型（0-普通件，1-密件）
        },
        // 新增：详情对话框控制
        incomingDetailVisible: false,
        outgoingDetailVisible: false,
        incomingDetailId: null,
        outgoingDetailId: null,
        selectedIncomingRows: [], // 收文表格选中的行
        selectedOutgoingRows: [], // 发文表格选中的行
      };
    },
    computed: {
      detailDialogTitle() {
        if (!this.currentDetail) return '文件详情';
        return `${this.currentDetail.fileNo || this.currentDetail.senderDocNo} - ${this.currentDetail.title}`;
      }
    },
    methods: {
      handleNodeClick(data) {
        if ([1, 2].includes(data.id)) {
          this.currentCategory = data;
          this.currentSubCategory = null;
          this.showIncomingTable = false;
          this.showOutgoingTable = false;
          return;
        }

        if ([11, 12].includes(data.id)) {
          this.currentCategory = this.treeData.find(item => item.id === 1);
          this.currentSubCategory = data;
          this.showIncomingTable = true;
          this.showOutgoingTable = false;
          this.loadIncomingData(1);
        }

        if ([21, 22].includes(data.id)) {
          this.currentCategory = this.treeData.find(item => item.id === 2);
          this.currentSubCategory = data;
          this.showIncomingTable = false;
          this.showOutgoingTable = true;
          this.loadOutgoingData(1);
        }
      },

      loadIncomingData(pageNum) {
        let isSecret = this.currentSubCategory.id;
        if (isSecret === 11) {
          this.query.secretType = 0;
          this.query.processType = '存档';
        } else if (isSecret === 12) {
          this.query.secretType = 1;
          this.query.processType = '存档';
        }
        if (pageNum) this.pageNum = pageNum;
        // 调用后端分页接口，传递查询条件、页码、页大小
        this.$request.get('/incomingDoc/selectPage', {
          params: {
            ...this.query,
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            // 展开查询条件（与后端IncomingDoc实体字段一一对应）
          }
        }).then(res => {
          if (res.code === '200') {
            let dataList = res.data.list;
            console.log("dataList", dataList)
            dataList.forEach(item => {
              item.objectName = item.objectName === '办公室' ? "未处理" : item.objectName;
            })
            this.tableData = dataList;    // 表格数据
            this.total = res.data.total;       // 总条数（用于分页）
          } else {
            this.$message.error(res.msg);
          }
        });
      },

      loadOutgoingData(pageNum) {
        let isSecret = this.currentSubCategory.id;
        if (isSecret === 21) {
          this.query.secretType = 0;
          this.query.archiveStatus = '存档';
        } else if (isSecret === 22) {
          this.query.secretType = 1;
          this.query.archiveStatus = '存档';
        }
        if (pageNum) this.pageNum = pageNum;
        // 调用后端分页接口，传递查询条件、页码、页大小
        this.$request.get('/outgoingDoc/selectPage', {
          params: {
            ...this.query,
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            // 展开查询条件（与后端IncomingDoc实体字段一一对应）
          }
        }).then(res => {
          console.log("res.data.list.objiecName" , res.data);
          if (res.code === '200') {
            let dataList = res.data.list;
            console.log("dataList", dataList)
            dataList.forEach(item => {
              item.objectName = item.objectName === '办公室' ? "未处理" : item.objectName;
            })
            this.tableData = dataList;    // 表格数据
            this.total = res.data.total;       // 总条数（用于分页）
          } else {
            this.$message.error(res.msg);
          }
        });
      },

      loadTableData(page) {
        if (this.showIncomingTable) {
          this.loadIncomingData(page);
        } else if (this.showOutgoingTable) {
          this.loadOutgoingData(page);
        }
      },

      handlePageChange(page) {
        this.pageNum = page;
        this.loadTableData(page);
      },

      handleDetail(row, type) {
        // 根据类型设置不同的ID变量
        if (type === 'incoming') {
          this.incomingDetailId = row.id;
          this.incomingDetailVisible = true;
          this.outgoingDetailVisible = false; // 确保发文对话框关闭
        } else if (type === 'outgoing') {
          this.outgoingDetailId = row.id;
          this.outgoingDetailVisible = true;
          this.incomingDetailVisible = false; // 确保收文对话框关闭
        }
      },

      exportData() {
        // 确定当前是收文还是发文
        const isIncoming = this.showIncomingTable;

        // 获取需要导出的数据
        const getExportData = async () => {
          let exportData = [];

          if (isIncoming) {
            // 收文导出
            if (this.selectedIncomingRows.length > 0) {
              // 使用选中的行数据
              exportData = this.selectedIncomingRows;
            } else {
              // 获取所有符合条件的收文数据
              const params = {
                ...this.query,
                pageNum: 1,
                pageSize: this.total, // 获取全部数据
                processType: '存档'
              };
              const res = await this.$request.get('/incomingDoc/selectPage', { params });
              if (res.code === '200') {
                exportData = res.data.list || [];
              } else {
                this.$message.error('导出数据获取失败：' + res.msg);
                return [];
              }
            }
          } else {
            // 发文导出
            if (this.selectedOutgoingRows.length > 0) {
              // 使用选中的行数据
              exportData = this.selectedOutgoingRows;
            } else {
              // 获取所有符合条件的发文数据
              const params = {
                ...this.query,
                pageNum: 1,
                pageSize: this.total, // 获取全部数据
                archiveStatus: '存档'
              };
              const res = await this.$request.get('/outgoingDoc/selectPage', { params });
              if (res.code === '200') {
                exportData = res.data.list || [];
              } else {
                this.$message.error('导出数据获取失败：' + res.msg);
                return [];
              }
            }
          }
          return exportData;
        };

        // 执行导出操作
        getExportData().then(data => {
          if (data.length === 0) {
            this.$message.warning('没有可导出的数据');
            return;
          }

          try {
            // 创建表头
            const headers = [
              '件号', '责任者', '文件编号', '题名', '日期', '密级',
              '页数', '备注', '盒号', '全宗号', '全宗名称', '年度',
              '保管期限', '机构或问题', '档号', '保管期限缩写',
              '门类代码', '门类名称', '机构问题缩写'
            ];

            // 映射数据 - 使用英文键名
            const mappedData = data.map((item, index) => ({
              serial: item.fileNo || '', // 件号
              responsible: '', // 责任者
              docNumber: isIncoming ? item.senderDocNo : item.senderDocNo, // 文件编号
              title: item.title || '', // 题名
              date:  ((isIncoming ? (item.receiveDate || '') : (item.createDate || '')).split(' ')[0]).replace(/-/g, ''), // 日期
              secretLevel: item.secretLevel || '', // 密级
              pageCount: item.pageCount || '', // 页数
              remark: '', // 备注
              boxNo: isIncoming ? item.boxNo : '', // 盒号
              fondsNo: '', // 全宗号
              fondsName: '', // 全宗名称
              annual: isIncoming ? item.annual : '', // 年度
              retentionPeriod: '', // 保管期限
              organization: '', // 机构或问题
              archiveNo: '', // 档号
              retentionAbbr: '', // 保管期限缩写
              categoryCode: '', // 门类代码
              categoryName: '', // 门类名称
              orgAbbr: '' // 机构问题缩写
            }));

            // 创建工作表 - 使用aoa_to_sheet确保表头和数据都正确
            const worksheet = XLSX.utils.json_to_sheet(mappedData);

            // 替换表头为中文
            const headerKeys = Object.keys(mappedData[0]);
            XLSX.utils.sheet_add_aoa(worksheet, [headers], { origin: 'A1' });

            // 创建工作簿并添加工作表
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, '文书档案');

            // 生成Excel文件并下载
            const fileName = `${isIncoming ? '收文' : '发文'}存档数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
            XLSX.writeFile(workbook, fileName);

            this.$message.success('导出成功');
          } catch (error) {
            console.error('导出失败:', error);
            this.$message.error('导出失败: ' + error.message);
          }
        });
      },
      // 处理收文表格选择变化
      handleIncomingSelectionChange(rows) {
        this.selectedIncomingRows = rows;
        console.log('收文表格选中行:', rows);
        // 这里可以添加其他业务逻辑
      },

      // 处理发文表格选择变化
      handleOutgoingSelectionChange(rows) {
        this.selectedOutgoingRows = rows;
        console.log('发文表格选中行:', rows);
        // 这里可以添加其他业务逻辑
      },
      handleSearch() {
        this.pageNum = 1;
        this.loadTableData();
      },
      resetSearch() {
        this.query.title = '';
        this.query.senderOrg = '';
        this.pageNum = 1;
        this.loadTableData();
      },
      handleIncomingPrint(id) {
        const tpl_name = "收发文新系统.ureport.xml";
        const pageIndex = 1;     // 页码
        const renderOption = 1;  // 渲染选项
        const url = `${this.$baseUrl}/ureport/preview?_u=mysql:${tpl_name}&_i=${pageIndex}&_r=${renderOption}&ids=${id}`;
        window.open(url, '_blank');
        document.getElementById(id).blur();
      },
      handleOutgoingPrint(id) {
        const tpl_name = "收发文新系统.ureport.xml";
        const pageIndex = 1;     // 页码
        const renderOption = 1;  // 渲染选项
        const url = `${this.$baseUrl}/ureport/preview?_u=mysql:${tpl_name}&_i=${pageIndex}&_r=${renderOption}&ids=${id}`;
        window.open(url, '_blank');
        document.getElementById(id).blur();
      },
      formatDate(dateString) {
        if (!dateString) return '';
        return dateString.split(' ')[0];
      }
    }
  }
</script>

<style>
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
  }

  body {
    background-color: #f5f7fa;
  }

  .archive-container {
    display: flex;
    min-height: calc(100vh - 60px);
    background-color: #fff;
    margin: 0px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.05);
  }

  .tree-container {
    width: 185px;
    background-color: #fff;
    border-right: 1px solid #e6e6e6;
    overflow: auto;
  }

  .content-container {
    flex: 1;
    padding: 0px;
    overflow-y: auto;
    background-color: #f8f9fc;
  }

  .tree-content {
    padding: 15px;
  }

  .tree-header {
    padding: 25px 20px 15px;
    border-bottom: 1px solid #eee;
  }

  .tree-header h2 {
    font-weight: 500;
    color: #303133;
    font-size: 22px;
    margin-bottom: 5px;
  }

  .tree-header p {
    color: #909399;
    font-size: 14px;
  }

  .el-tree-node__content {
    height: 46px;
    font-size: 16px;
  }

  .el-tree-node__label {
    font-weight: normal;
  }

  .el-tree-node__content:hover {
    background-color: #f0f7ff;
  }

  .el-tree-node.is-current > .el-tree-node__content {
    background-color: #f0f7ff;
    color: #409eff;
    font-weight: bold;
  }

  .table-container {
    background: #fff;
    border-radius: 6px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.06);
    margin-bottom: 30px;
  }

  .operation-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 5px;
    padding: 15px 20px;
    background: #fff;
    border-radius: 6px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.06);
  }

  .selected-category {
    font-size: 18px;
    font-weight: 500;
    color: #303133;
  }

  .current-approver {
    padding: 4px 8px;
    background: #e6f7ff;
    border-radius: 3px;
    color: #1890ff;
    display: inline-block;
  }

  .approver-waiting {
    background: #fff7e6;
    color: #fa8c16;
  }

  .pagination-container {
    margin-top: 30px;
    text-align: center;
  }

  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 70vh;
    background: #fff;
    border-radius: 6px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.06);
  }

  .empty-icon {
    font-size: 60px;
    color: #c0c4cc;
    margin-bottom: 20px;
  }

  .empty-text {
    font-size: 18px;
    color: #909399;
    margin-bottom: 30px;
  }

  .detail-btn {
    color: #1890ff;
    background-color: #e6f7ff;
    border-color: #91d5ff;
  }

  .system-header {
    background-color: #001529;
    color: white;
    height: 60px;
    display: flex;
    align-items: center;
    padding: 0 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  }

  .system-title {
    font-size: 20px;
    font-weight: 600;
    margin-left: 15px;
  }

  .system-logo {
    width: 40px;
    height: 40px;
    background-color: #1890ff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
  }
  /* 新增搜索区域样式 */
  .search-group {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .search-input {
    width: 200px; /* 缩短搜索框宽度 */
  }

  .search-button, .reset-button {
    margin-left: 0;
  }

  .export-section {
    margin: 15px 0;
    padding: 0 20px;
  }

  /* 响应式调整 */
  @media (max-width: 1200px) {
    .search-group {
      flex-wrap: wrap;
    }

    .search-input {
      width: 180px;
    }
  }
</style>
